<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\admin\controller\apply\Confg;
use app\admin\model\config\Basics;
use app\admin\model\deal\Order;
use app\admin\model\memberpoint\Fellow;
use app\admin\model\memberpoint\Integral;
use app\admin\model\nursery\Attestation;
use app\admin\model\nursery\Companyattestation;
use app\admin\model\order\Userorder;
use app\admin\model\Shop;
use app\admin\model\shop\ShopPrints;
use app\admin\model\User;
use app\common\controller\Api;
use app\common\handler\TimeHandler;
use app\common\keloop\Base;
use app\common\keloop\Delivery;
use app\common\keloop\KeloopSdk;
use app\common\model\Attachment;
use app\common\model\ScoreLog;
use feie\FeiE;
use think\Db;
use think\Log;
use think\Model;
use think\Validate;

/**
 *  微信
 */
class Wechat extends Api
{
    protected $noNeedLogin = ['weChatPay','userNotifyx','orderNotifyx','orderCancelNotifyx','orderDaDaNotifyx'];
    protected $noNeedRight = '*';
    protected $model ='';
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 微信支付
     */
    public function weChatPay()
    {
        $type = $this->request->param('type');
        $returnurl = $this->request->param('returnurl', '');
        $user = $this->auth->getUser();

        //1 会员购买  2代付
        if($type == 'hy'){
            $title = "购买会员";
            $orderid = "wx".time().rand(100000,999999);
            $Confg = Basics::get(1);

            //获取配置文件中的金额
            $amount = $Confg['member_price'];
            $result  = $this->userOrderCreate($orderid,$amount,$Confg);
            $notifyurl = $this->request->domain() . "/api/wechat/userNotifyx";

        }else{
            $title = "代付";
            $order_number= $this->request->param('order_number');
            $result = \app\admin\model\shop\Order::get(['order_number'=>$order_number]);
            if(!$result) $this->error("订单不存在");
            $orderid = $order_number;
            $amount = $result['actual_price'];
            if (!$amount || $amount < 0) {
                $this->error("支付金额必须大于0");
            }
            $notifyurl = $this->request->domain() . "/api/wechat/orderNotifyx";
        }
        if(!$result)   $this->error('生成订单失败');
        $data = [
            'amount'=> $amount,//支付金额
            'orderid'=>  $orderid,//"订单号",
            'type' =>  "wechat",//wechat 微信  alipay支付宝
            'title'=> $title,
            'notifyurl'=> $notifyurl,//"回调地址",
            'returnurl'=> $returnurl,
            'method'=>"miniapp", //支付环境  miniapp(微信小程序)
            'openid'=> $user["openid"],//"用户的OpenID",
        ];
        Log::log([
            '会员支付'=>$data,
        ]);
        $result =  \addons\epay\library\Service::submitOrder($data);
        if(isset($result['appId'])){
            $this->success("请求成功", $result);
        }
        $this->error("请求失败", $result);

    }


    /**
     * @param $type
     * @param $orderid
     * @param $amount
     * @param $Confg
     * @return Userorder
     * 用户购买会员
     */
    private function userOrderCreate($orderid,$amount,$Confg){
        $user = $this->auth->getUser();
        $data=[
            'uid' => $user['id'],
            'member_day'=>$Confg['member_day'],
            'price'=>$Confg['member_price'],
            'status'=>1,
            'order_number'=>$orderid,
            'price'=>$amount,
            'order_time'=>date('Y-m-d H:i:s'),
        ];
        return Userorder::create($data);
    }



    /**
     * 会员支付成功回调
     */
    public function userNotifyx()
    {
        $paytype = $this->request->param('paytype','wechat');
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();
        Log::log([
            'hd'=>$data,
            'out_trade_no'=>$data['out_trade_no'],
            'transaction_id'=>$data['transaction_id'],
            'msg'=>'会员支付成功'
        ]);
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            $result= (new Userorder())->where(['order_number'=>$out_trade_no])->find();
            if($result){
                Db::startTrans();
                $res = Userorder::update(['status'=>2,'payment_time'=>date('Y-m-d H:i:s'),'transaction_id'=>$data['transaction_id']],['order_number'=>$out_trade_no]);
                if(!$res) {
                    Db::rollback();
                    return false;
                }
                $member_expire_time = date('Y-m-d H:i:s',strtotime("+ ".$result['member_day']."  day", time()));
                $res = User::update(['member_expire_time'=>$member_expire_time],['id'=>$result['uid']]);
                if(!$res) {
                    Db::rollback();
                    return false;
                }
            }else{
                $this->error('该订单不存在');
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error('支付失败',$e->getMessage());
        }
        //下面这句必须要执行,且在此之前不能有任何输出
        return $pay->success()->send();
    }


    /**
     * 订单支付成功回调
     */
    public function orderNotifyx()
    {
        $paytype = $this->request->param('paytype','wechat');
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            $orderInfo= (new \app\admin\model\shop\Order())->where(['order_number'=>$out_trade_no])->find();
            if($orderInfo){
                $user = User::get(['openid'=>$data['openid']]);
                $datas['payment_user_id'] = $user['id'];
                $datas['payment_time']=date('Y-m-d H:i:s');
                $datas['transaction_id']=$data['transaction_id'];
                if($orderInfo['is_hy_order'] == '1'){
                    $datas['status'] =1;
                    \app\admin\model\shop\Order::update($datas,['order_number'=>$out_trade_no]);
                }else{
                    $datas['status'] =2;
                    $shopInfo = Shop::get($orderInfo['shop_id']);
                    if($shopInfo['is_voluntarily_order'] == '1'){
                        $res = Delivery::addDadaOrder($orderInfo);
                        if($res['code'] == 0){
                            $datas['status'] =3;
                        }
                    }
                    \app\admin\model\shop\Order::update($datas,['order_number'=>$out_trade_no]);
                    if($shopInfo['is_voluntarily_print'] == '1'){
                        $printInfo = (new ShopPrints())->printInfo($orderInfo['shop_id']);
                        if($printInfo){
                            (new FeiE())->printMsg($printInfo['sn'],$orderInfo,1);
                        }
                    }
                }
            }else{
                $this->error('该订单不存在');
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error('支付失败',$e->getMessage());
        }
        //下面这句必须要执行,且在此之前不能有任何输出
        return $pay->success()->send();
    }


    /**
     * 订单退款成功回调
     */
    public function orderCancelNotifyx()
    {
        Log::log([
            'msg'=>'退款回调成功'
        ]);
        $paytype = $this->request->param('paytype','wechat');
        $pay = Service::checkNotify($paytype);
        Log::log([
            'msg'=>'退款回调成功'
        ]);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();
        Log::log([
            'hd'=>$data,
            'msg'=>'退款回调成功'
        ]);
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            $result= (new \app\admin\model\shop\Order())->where(['order_number'=>$out_trade_no])->find();
            if($result){
                Db::startTrans();
                $result = \app\admin\model\shop\Order::update(
                    [
                    'refund_status'=>2,
                    'refund_time'=>date('Y-m-d H:i:s'),
                    'transaction_id'=>$data['transaction_id']
                    ],
                    ['order_number'=>$out_trade_no]);
                if(!$result) {
                    Db::rollback();
                    return false;
                }
            }else{
                $this->error('该订单不存在');
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error('退款失败',$e->getMessage());
        }
        //下面这句必须要执行,且在此之前不能有任何输出
        return $pay->success()->send();
    }


    /**
     * 快跑者订单回调
     */
    public function orderKeloopNotifyx()
    {
        $param = $_POST;
        // 创建 SDK 实例
        $sdk = new KeloopSdk();
        // 调用 checkSign 方法
        $sign = $sdk->checkSign($param);
        // 业务逻辑处理
        if (false === $sign) {
            exit('验签失败');
        }
        Log::log([
            'title'=>'快跑者订单回调',
            'msg'=>$param
        ]);
        try {
            $result= (new \app\admin\model\shop\Order())->where(['order_number'=>$param['note']])->find();
            if($result){
                $data['keloop_status'] = $param['state'];
                if(in_array($param['state'],['3','4','7','9'])){ //3(待接单) 4(取单中) 7(商户或团队撤销) 9(骑手到店)
                    $data['status'] = 4;
                }elseif($param['state'] == '5'){ //送单中(已取单)
                    $data['status'] = 5;
                } elseif($param['state'] == '6'){ //已送达
                    $data['status'] = 6;
                }
                $result = \app\admin\model\shop\Order::update($data,['order_number'=>$param['note']]);
                if($result){
                    exit('success');
                }
            }else{
                exit('订单不存在');
            };
        } catch (Exception $e) {
            exit('接口调用异常：' . $e->getMessage());
        }
    }


    /**
     * 达达订单回调
     */
    public function orderDaDaNotifyx()
    {
//        var_dump(Delivery::getOrderTrack(['order_number'=>'wx16780704941063871']));exit;
        $input = file_get_contents('php://input');
        $param = json_decode($input, true);
        Log::log([
            'dada'=>'达达订单回调',
            'msg'=>$param
        ]);
        $data =[
            'dada_status'=>$param['order_status']
        ];
        if($param['order_status'] == 3){
            $data['status'] = 5;
        }elseif($param['order_status'] == 4){
            $data['status'] = 6;
            $data['service_time'] = date('Y-m-d H:i:s');
        }elseif($param['order_status'] == 8){
            $data['status'] = 4;
        }
        \app\admin\model\shop\Order::update($data,['order_number'=>$param['order_id']]);
        $this->success('请求成功',null,200);
    }





}
